let formatTimeZH = (date) => {

  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();
  const hour = date.getHours();
  const minute = date.getMinutes();
  const second = date.getSeconds();

  return year + '年' + month + '月' + day + '日' + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

let formatNumber = (n) => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

let InitArticleList = (cb) => {

  let tableId = getApp().globalData.private_article_tableId,
    Articles = new wx.BaaS.TableObject(tableId),
    Article = Articles.create()

  var now = new Date();

  let data = {
    'user_id': wx.BaaS.storage.get('uid'),
    'title': "3. 左滑 ← 删除或分享灵感",
    'intro': "3. 左滑 ← 删除或分享灵感",
    'content': '[{ rownum: 1, label: "normal", content: "", imageurl: "none" }]',
    'updated_time': formatTimeZH(new Date()), 
    'created_at': Date.parse(now) + 2,
    'updated_at': Date.parse(now) + 2,
  }

  Article.set(data)
    .save()
    .then(res => {  })
    .catch(err => console.dir(err))

  Article = Articles.create()

  data = {
    'user_id': wx.BaaS.storage.get('uid'),
    'title': "2. 长按添加按钮语音快速添加",
    'intro': "2. 长按添加按钮语音快速添加",
    'content': '[{ rownum: 1, label: "normal", content: "", imageurl: "none" }]',
    'updated_time': formatTimeZH(new Date()),
    'created_at': Date.parse(now) + 3,
    'updated_at': Date.parse(now) + 3,
  }

  Article.set(data)
    .save()
    .then(res => { })
    .catch(err => console.dir(err))

  Article = Articles.create()

  data = {
    'user_id': wx.BaaS.storage.get('uid'),
    'title': "1. 点击添加按钮添加灵感",
    'intro': "1. 点击添加按钮添加灵感",
    'content': '[{ rownum: 1, label: "normal", content: "", imageurl: "none" }]',
    'updated_time': formatTimeZH(new Date()),
    'created_at': Date.parse(now) + 4,
    'updated_at': Date.parse(now) + 4,
  }

  Article.set(data)
    .save()
    .then(res => { })
    .catch(err => console.dir(err))

  Article = Articles.create()

  


  data = {
    'user_id': wx.BaaS.storage.get('uid'),
    'title': "   《源来：用户手册》",
    'intro': "",
    'content': '[{ rownum: 1, label: "normal", content: "", imageurl: "none" }]',
    'updated_time': formatTimeZH(new Date()),
    'created_at': Date.parse(now.toUTCString()) + 5,
    'updated_at': Date.parse(now.toUTCString()) + 5,
  }

  Article.set(data)
    .save()
    .then(res => { cb(res) })
    .catch(err => console.dir(err))

}

let addArticle = (ctx,cb) => {
  let tableId = getApp().globalData.private_article_tableId,
        Articles = new wx.BaaS.TableObject(tableId),
        Article = Articles.create()
    
    let data = {
      'user_id': wx.BaaS.storage.get('uid'),
        'title' : ctx.data.article.title,
        'intro' : ctx.data.article.intro,
        'content' : JSON.stringify(ctx.data.article),
        'updated_time': formatTimeZH(new Date())
    }

    Article.set(data)
        .save()
        .then(res => cb(res))
        .catch(err => console.dir(err))
}

let updateArticle = (ctx,cb) => {
  let tableId = getApp().globalData.private_article_tableId,
    recordId = ctx.data.curRecordId;
  let Articles = new wx.BaaS.TableObject(tableId),
    Article = Articles.getWithoutData(recordId)

  let data = {
    'user_id': wx.BaaS.storage.get('userinfo').id,
    'title': ctx.data.article.title,
    'intro': ctx.data.article.intro,
    'content': JSON.stringify(ctx.data.article),
    'updated_time': formatTimeZH(new Date())
  }

  Article.set(data)
    .update()
    .then(res => cb(res))
    .catch(err => console.dir(err))
}

let deleteArticlePrivate = (article_id, cb) => {
  let tableId = getApp().globalData.private_article_tableId,
    Articles = new wx.BaaS.TableObject(tableId)
    
    Articles.delete(article_id).then(res => {
      cb(res)
    },err => {
      cb(err)
    })
}

let deleteArticleFork = (article_id,cb) => {
  unFork(article_id,cb)
}


let updataArticleFork = (ctx,cb) => {

  let tableId = getApp().globalData.fork_article_tableId,
    recordId = ctx.data.curRecordId;
  let Articles = new wx.BaaS.TableObject(tableId),
    Article = Articles.getWithoutData(recordId)

  let data = {
    'user_id': wx.BaaS.storage.get('userinfo').id,
    'title': ctx.data.article.title,
    'intro': ctx.data.article.intro,
    'content': JSON.stringify(ctx.data.article),
    'updated_time': formatTimeZH(new Date())
  }

  Article.set(data)
    .update()
    .then(res => cb(res))
    .catch(err => console.dir(err))

}


let getArticleEdit = (article_id,cb) => {
  let tableId = getApp().globalData.private_article_tableId
  let Articles = new wx.BaaS.TableObject(tableId)

  Articles.get(article_id).then(res => cb(res),err => cb(err))
}

let getArticleRead = (article_id, cb) => {
  let tableId = getApp().globalData.public_article_tableId
  let Articles = new wx.BaaS.TableObject(tableId)

  Articles.expand('created_by').get(article_id).then(res => cb(res), err => cb(err))
}

let getArticleForkEdit = (article_id, cb) => {
  let tableId = getApp().globalData.fork_article_tableId
  let Articles = new wx.BaaS.TableObject(tableId)

  Articles.get(article_id).then(res => cb(res), err => cb(err))
}

let getPrivateArticleList = (user_id, success,err) => {
  let tableId = getApp().globalData.private_article_tableId
  let Articles = new wx.BaaS.TableObject(tableId)

  let query = new wx.BaaS.Query()

  query.compare('user_id', '=', user_id)

  Articles.setQuery(query).limit(1000).orderBy(['-updated_at']).find().then(res => success(res),err => err(err))
}

let getForkArticleList = (user_id, success, err) => {
  let tableId = getApp().globalData.fork_article_tableId
  let Articles = new wx.BaaS.TableObject(tableId)

  let query = new wx.BaaS.Query()

  query.compare('user_id', '=', user_id)

  Articles.setQuery(query).limit(1000).orderBy(['-updated_at']).find().then(res => success(res), err => err(err))
  
}

let getForkFromYouArticleList = (article_id, success, err) => {
  let tableId = getApp().globalData.fork_article_tableId
  let Articles = new wx.BaaS.TableObject(tableId)

  let query = new wx.BaaS.Query()

  query.compare('origin_article_id', '=', article_id)

  Articles.setQuery(query).limit(100).expand('created_by').orderBy(['-top','-updated_at',]).find().then(res => success(res), err => err(err))
}

let deletePusblishArticle = (article_id,success,err) => {

  let tableId = getApp().globalData.public_article_tableId
  let Articles = new wx.BaaS.TableObject(tableId)

  let Article = Articles.getWithoutData(article_id)
  Article.set('is_delete',true)

  Article.update().then(res => {
    // success
    success(res)
  }, err => {
    // err
    err(err)
  })

}

let getPublishArticleList = (success, err) => {
  let tableId = getApp().globalData.public_article_tableId
  let Articles = new wx.BaaS.TableObject(tableId)

  let query = new wx.BaaS.Query()

  query.compare('user_id', '=', wx.BaaS.storage.get('uid'))
  query.compare('is_delete', '=', false)

  Articles.setQuery(query).limit(1000).expand('created_by').orderBy(['-updated_at']).find().then(res => success(res), err => err(err))
}

let publishArticle = (article_id,intro,tags,title, success, err) => {

  let privateArticleTableId = getApp().globalData.private_article_tableId
  let PrivateArticles = new wx.BaaS.TableObject(privateArticleTableId)

  let publicArticleTableId = getApp().globalData.public_article_tableId
  let PublicArticles = new wx.BaaS.TableObject(publicArticleTableId)
  let Article = PublicArticles.create()


  PrivateArticles.get(article_id).then(res => {

    var article = JSON.parse(res.data.content)

    let data = {
      'user_id': wx.BaaS.storage.get('userinfo').id,
      'title': title,
      'intro': intro,
      'tags' : tags,
      'content': JSON.stringify(article),
      'updated_time': formatTimeZH(new Date())
    }

    Article.set(data)
      .save()
      .then(res => success(res))
      .catch(err => console.dir(err))

  }, err => err(err))

}

let getImpactArticleList = (tags,limit,offset,success, err) => {
  let tableId = getApp().globalData.public_article_tableId
  let Articles = new wx.BaaS.TableObject(tableId)

  let query = new wx.BaaS.Query()
  
  if(tags != null && tags.length > 0) {
    query.arrayContains('tags', tags)
  }
  query.compare('is_delete', '=', false)

  Articles.setQuery(query).expand('created_by').orderBy([['-forks','-stars',  '-updated_at']]).limit(limit).offset(offset).find().then(res => success(res), err => err(err))
}

let zan = (article_id,cb) =>{

  let tableId = getApp().globalData.star_tableId
  let Zans = new wx.BaaS.TableObject(tableId)
  let zan = Zans.create()

  let data = {
    "user_id" : wx.BaaS.storage.get("uid"),
    "article_id" : article_id
  }

  zan.set(data)
    .save()
    .then(res => cb(res))
    .catch(err => cb(err))

    let publicArticleTableId = getApp().globalData.public_article_tableId
    let PublicArticles = new wx.BaaS.TableObject(publicArticleTableId)
  
    let article = PublicArticles.getWithoutData(article_id)
    article.incrementBy("stars",1)
    article.update().then(res => {},err => { console.error(err) })
}

let unZan = (article_id,cb) => {
  let tableId = getApp().globalData.star_tableId
  let Zans = new wx.BaaS.TableObject(tableId)

  let query = new wx.BaaS.Query()
  query.compare('user_id',"=", wx.BaaS.storage.get("uid"))
  query.compare("article_id","=",article_id)

  Zans.delete(query).then(res => cb(res),err => cb(err))

  let publicArticleTableId = getApp().globalData.public_article_tableId
  let PublicArticles = new wx.BaaS.TableObject(publicArticleTableId)

  let article = PublicArticles.getWithoutData(article_id)
  article.incrementBy("stars",-1)
  article.update().then(res => {},err => { console.error(err) })
}

let isZan = (article_id,cb) => {
  let tableId = getApp().globalData.star_tableId
  let Zans = new wx.BaaS.TableObject(tableId)

  let query = new wx.BaaS.Query()
  query.compare('user_id','=', wx.BaaS.storage.get("uid"))
  query.compare("article_id", '=', article_id)

  Zans.setQuery(query).find().then(res => {
    cb(res)
  },err => {
    cb(err)
  })
}

let fork = (article_id, cb) => {

  let tableId = getApp().globalData.fork_tableId
  let Forks = new wx.BaaS.TableObject(tableId)
  let fork = Forks.create()

  let data = {
    "user_id": wx.BaaS.storage.get("uid"),
    "article_id": article_id
  }

  fork.set(data)
    .save()
    .then(res => {})
    .catch(err => cb(err))

  let publicArticleTableId = getApp().globalData.public_article_tableId
  let PublicArticles = new wx.BaaS.TableObject(publicArticleTableId)

  let article = PublicArticles.getWithoutData(article_id)
  article.incrementBy("forks", 1)
  article.update().then(res => { }, err => { console.error(err) })

  PublicArticles.get(article_id)
    .then((res) => {

      let forkArticleTableId = getApp().globalData.fork_article_tableId
      let ForkArticles = new wx.BaaS.TableObject(forkArticleTableId)
      let forkArticle = ForkArticles.create()

      let articleData = {
        'user_id': wx.BaaS.storage.get("uid"),
        'origin_article_id': res.data.id,
        'article_author_id': res.data.user_id,
        'title': res.data.title,
        'intro': res.data.intro,
        'content': res.data.content,
        'updated_time': formatTimeZH(new Date())
      }

      forkArticle.set(articleData)
        .save()
        .then(res => cb(res))
        .catch(err => console.dir(err))

    })
}

let unFork = (article_id, cb) => {
  let tableId = getApp().globalData.fork_tableId
  let Forks = new wx.BaaS.TableObject(tableId)

  let query = new wx.BaaS.Query()
  query.compare('user_id', "=", wx.BaaS.storage.get("uid"))
  query.compare("article_id", "=", article_id)

  Forks.delete(query).then(res => {}, err => cb(err))

  let publicArticleTableId = getApp().globalData.public_article_tableId
  let PublicArticles = new wx.BaaS.TableObject(publicArticleTableId)

  let article = PublicArticles.getWithoutData(article_id)
  article.incrementBy("forks", -1)
  article.update().then(res => { }, err => { console.error(err) })

  let forkArticleTableId = getApp().globalData.fork_article_tableId
  let ForkArticles = new wx.BaaS.TableObject(forkArticleTableId)
  
  query = new wx.BaaS.Query()
  query.compare('user_id', "=", wx.BaaS.storage.get("uid"))
  query.compare("origin_article_id", "=", article_id)

  ForkArticles.delete(query).then(res => cb(res), err => cb(err))

}

let isFork = (article_id, cb) => {
  let tableId = getApp().globalData.fork_tableId
  let Forks = new wx.BaaS.TableObject(tableId)

  let query = new wx.BaaS.Query()
  query.compare('user_id', '=',  wx.BaaS.storage.get("uid"))
  query.compare("article_id", '=',  article_id)

  Forks.setQuery(query).find().then(res => {
    cb(res)
  }, err => {
    cb(err)
  })
}

let setForkFromYouArticleTop = (article_id, success, err) => {
  let tableId = getApp().globalData.fork_article_tableId
  let Articles = new wx.BaaS.TableObject(tableId)

  let Article = Articles.getWithoutData(article_id)

  Article.set('top',1)

  Article.update().then(res => {
    // success
    success(res)
  }, err => {
    // err
    err(err)
  })

}

let getSearchArticleList = (keyworld, limit,offset,success, err) => {
  let tableId = getApp().globalData.public_article_tableId
  let Articles = new wx.BaaS.TableObject(tableId)


  let query = new wx.BaaS.Query()

  query.contains('content', keyworld)

  Articles.setQuery(query).expand('created_by').orderBy([['-forks', '-stars', '-updated_at']]).limit(limit).offset(offset).find().then(res => success(res), err => err(err))
}



module.exports = {
  addArticle, updateArticle, getArticleEdit, getArticleRead, getArticleForkEdit, getImpactArticleList, getForkArticleList, updataArticleFork, deleteArticlePrivate, deleteArticleFork, InitArticleList, getForkFromYouArticleList, deletePusblishArticle,
  publishArticle, getPrivateArticleList, getPublishArticleList, zan, unZan, fork, unFork, isZan, isFork, setForkFromYouArticleTop, getSearchArticleList
}